import os
import random
from datetime import datetime
from typing import List

from PIL import Image
from fastapi import UploadFile, File
from loguru import logger
from pydantic import BaseModel

from utils.common_util import get_server_image_storage_path_by_os


class PictureUtil(BaseModel):
    @classmethod
    def save_upload_picture(cls, storage_path: str = '__tmp__', file: UploadFile = File(...)) -> List[str]:
        """
        写入并保存单个文件
        :param storage_path:
        :param file:
        :return: 生成的图片名称
        """
        local_system_path = get_server_image_storage_path_by_os()

        local_storage_path = os.path.join(local_system_path, storage_path)
        os.makedirs(os.path.abspath(local_storage_path), exist_ok=True)

        contents = file.file.read()
        f, e = os.path.splitext(file.filename)
        # 获取当前时间戳
        timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
        # 生成随机数
        randnum = str(random.randint(1000, 9999))
        # 拼接文件名
        out_file_name = timestamp + randnum + str(e)
        with open(os.path.join(local_storage_path, out_file_name), "wb") as buffer:
            buffer.write(contents)
            buffer.close()

        return out_file_name

    @classmethod
    def gen_thumbnails(cls, file_name: str, size=(700, 472)):
        """
        批量生成缩略图
        :param files_name:
        :param size: 700 x 472
        :return:
        """

        outfile = os.path.splitext(file_name)[0] + ".thumbnail.png"
        if file_name != outfile:
            try:
                with Image.open(file_name) as img:
                    img.thumbnail(size)
                    img.save(outfile, 'PNG', quality=90)
                return outfile
            except OSError as e:
                logger.info("cannot create thumbnail for", file_name)
                logger.error(e)

    # def save_original_picture(cls, storage_path: str = '__tmp__', files: List[UploadFile] = File(...)) -> List[str]:
    #     local_storage_path = PictureServiceConfig.SERVER_LOCAL_STORAGE_PATH.join(storage_path)
    #     for file in files:
    #         f, e = os.path.splitext(file)
    #         out_file_name = base64.b64encode(f.encode('utf-8')).join(e)
    #         try:
    #             with Image.open(BytesIO(file)) as img:
    #                 img.save(local_storage_path, file)
    #     return
